package chat.keepWind.event;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;

import chat.keepWind.bean.DataPackage;
import chat.keepWind.handle.KeepWindDecoder;
import chat.keepWind.handle.KeepWindEncoder;
import chat.keepWind.handle.SndFileInboundHandler;
import chat.keepWind.util.GlobalConst;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

public class SendFile {
	
	public void send(final String remoteIp,DataPackage filePkg) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();
        Channel channel = null;
        try {
            bootstrap.group(eventLoopGroup).channel(NioDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            pipeline.addLast(new KeepWindDecoder()); //解密
                            pipeline.addLast(new KeepWindEncoder(new InetSocketAddress(remoteIp,GlobalConst.FILE_PORT))); //编码
                            pipeline.addLast(new SndFileInboundHandler());//处理数据
                        }
                    });
            channel = bootstrap.bind(0).sync().channel();
            
            
        	File file = new File(filePkg.getSrcPath());
        	
        	//文件不存在
        	if(!file.isFile()){
        		try {
            		filePkg.setFileLen(0);
    				channel.writeAndFlush(filePkg).sync();
    				channel.closeFuture();
    			} catch (InterruptedException e1) {
    				e1.printStackTrace();
    			}
        		return;
        	}
        	
            long len = file.length();
                
            RandomAccessFile raf = new RandomAccessFile(file, "r");
          
            raf.seek(0); 
            
            byte[] bytes = null;
            if(len>=GlobalConst.BYTE_NUM){
            	bytes = new byte[GlobalConst.BYTE_NUM];
            }else{
            	bytes = new byte[(int)len];
            }
            raf.read(bytes);//读取
            filePkg.setMsgContent(bytes);
            filePkg.setFileNo(1);
            int port = ((InetSocketAddress)channel.localAddress()).getPort();
            filePkg.setPort(port);
            
            raf.close();
            
            channel.writeAndFlush(filePkg).sync();
            
          
            channel.closeFuture().sync();
            
        } catch (Exception e) {
            //e.printStackTrace();
        	//出错
        	try {
        		filePkg.setFileLen(0);
				channel.writeAndFlush(filePkg).sync();
				channel.closeFuture();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
        } finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
